import redis
import json
from datetime import datetime
from django.conf import settings

# Redis连接配置
redis_client = redis.Redis(
    host=settings.REDIS_CONFIG['host'],
    port=settings.REDIS_CONFIG['port'],
    db=settings.REDIS_CONFIG['db'],
    decode_responses=True,
    encoding='utf-8'
)

class ChatRedisService:
    """聊天Redis服务类"""
    
    @staticmethod
    def save_chat_messages(session_id, messages):
        """保存聊天消息到Redis"""
        key = f"chat:session:{session_id}:messages"
        redis_client.setex(key, 86400 * 7, json.dumps(messages))  # 保存7天
    
    @staticmethod
    def get_chat_messages(session_id):
        """从Redis获取聊天消息"""
        key = f"chat:session:{session_id}:messages"
        data = redis_client.get(key)
        if data:
            return json.loads(data)
        return []
    
    @staticmethod
    def save_session_info(session_id, title, user_id):
        """保存会话信息到Redis"""
        key = f"chat:session:{session_id}:info"
        info = {
            'title': title,
            'user_id': user_id,
            'created_at': datetime.now().isoformat(),
            'updated_at': datetime.now().isoformat()
        }
        redis_client.setex(key, 86400 * 7, json.dumps(info))  # 保存7天
    
    @staticmethod
    def get_session_info(session_id):
        """获取会话信息"""
        key = f"chat:session:{session_id}:info"
        data = redis_client.get(key)
        if data:
            return json.loads(data)
        return None
    
    @staticmethod
    def delete_session(session_id):
        """删除会话"""
        # 删除消息
        messages_key = f"chat:session:{session_id}:messages"
        redis_client.delete(messages_key)
        # 删除会话信息
        info_key = f"chat:session:{session_id}:info"
        redis_client.delete(info_key)
    
    @staticmethod
    def get_user_sessions(user_id):
        """获取用户的所有会话列表"""
        pattern = f"chat:session:*:info"
        keys = redis_client.keys(pattern)
        sessions = []
        
        for key in keys:
            data = redis_client.get(key)
            if data:
                info = json.loads(data)
                if info.get('user_id') == user_id:
                    session_id = key.split(':')[2]
                    sessions.append({
                        'session_id': session_id,
                        'title': info.get('title'),
                        'created_at': info.get('created_at'),
                        'updated_at': info.get('updated_at')
                    })
        
        # 按更新时间排序
        sessions.sort(key=lambda x: x['updated_at'], reverse=True)
        return sessions
